﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StudyCompanion.Commons.Result;

namespace StudyCompanion.Commons.Filters;

/// <summary>
///     参数验证
/// </summary>
public class GlobalValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0)
                .SelectMany(v => v.Errors)
                .Select(v => v.ErrorMessage)
                .ToList();

            var responseObj = new CommonResult
            {
                Code = 400,
                Message = $"请求参数错误:{string.Join(";", errors)}"
            };

            context.Result = new JsonResult(responseObj)
            {
                StatusCode = 200
            };
        }
    }
}